local System = require"ecs/system/system"

local area_process_system =  class("AreaProcessSystem",System){
    system_config = {
        type = SYSYTEM_TYPE_PROCESS;
        is_default_add = true;
        filter = {"SandboxAreaComponent"};
    },

    sandbox = nil;
}

function area_process_system:_init()
    self.sandbox = box_core.get_shared("Sandbox")
end

function area_process_system:get_area_status(area)
    local ax,ay = area.x,area.y
    local sandbox = self.sandbox
    local ldx,ldy = sandbox.loading_center.x,sandbox.loading_center.y
    local st_min_x,st_min_y = ldx - sandbox.stop_size,ldy - sandbox.stop_size
    local st_max_x,st_max_y = ldx + sandbox.stop_size,ldy + sandbox.stop_size
    if ax > st_max_x or ay > st_max_y or ax < st_min_x or ay < st_min_y then
        return AREA_STATUS_RECYCLING
    end
    local ld_min_x,ld_min_y = ldx - sandbox.loading_size,ldy - sandbox.loading_size
    local ld_max_x,ld_max_y = ldx + sandbox.loading_size,ldy + sandbox.loading_size
    if ax > ld_max_x or ay > ld_max_y or ax < ld_min_x or ay < ld_min_y then
        return AREA_STATUS_STOP
    end
    return AREA_STATUS_LOADING
end

function area_process_system:preProcess(dt)
    local sandbox = self.sandbox
    local ldx,ldy = sandbox.loading_center.x,sandbox.loading_center.y
    local up_ldx,up_ldy = sandbox.loading_center.up_x,sandbox.loading_center.up_y
    
    if up_ldx ~= ldx or up_ldy ~= ldy then
        self.sandbox.loading_center.up_x = ldx
        self.sandbox.loading_center.up_y = ldy

        for ax = ldx - sandbox.loading_size,ldx + sandbox.loading_size do
            for ay = ldy - sandbox.loading_size,ldy + sandbox.loading_size do
                local area = sandbox:get_area(ax,ay)
                --self.sandbox.loading_areas[area] = area
                tiny.addEntity(box_core.world,area)
            end
        end
    end
end

function area_process_system:process(area,dt)
    local status = self:get_area_status(area)
    area.status = status
    if status ~= AREA_STATUS_LOADING then
        tiny.removeEntity(box_core.world,area)
    end
end

return area_process_system()

